package com.glamour.hlcity.module.node.filter;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.Attribute;
import org.htmlparser.Node;
import org.htmlparser.Tag;
import org.htmlparser.filters.HasAttributeFilter;

import com.glamour.hlcity.common.util.ListUtil;

public class AttributeQueryListFilter extends HasAttributeFilter {
	private List<Attribute> attributeList=ListUtil.emptyList();
	private static final long serialVersionUID = -3838272490911220928L;
	public AttributeQueryListFilter(){
		
		
	}
	public AttributeQueryListFilter(List<Attribute> attributeList){
		if(attributeList==null){
			this.attributeList=ListUtil.emptyList();
		}else{
			this.attributeList=attributeList;
		}
	}
	
	public AttributeQueryListFilter(String attribute, String value) {
		super(attribute, value);
		
	}
	public AttributeQueryListFilter(String attribute) {
		super(attribute);
	}
	
	
	public void setAttributeList(List<Attribute> attributeList) {
		this.attributeList = attributeList;
	}

	public Attribute getAttribute(Node node){
		if(node instanceof Tag){
			return ((Tag) node).getAttributeEx(getAttributeName());
		}
		return null;
	}
	
	/**
	 * 过滤
	 * <ul>
	 * <li>存在特定的一个属性</li>
	 * <li>存在特定的一个属性和特定的属性值</li>
	 * <li>存在特定的属性数组系列</li>
	 * </ul>
	 */
	@Override
	public boolean accept(Node node) {
		if (!StringUtils.isBlank(mAttribute)) {
			Attribute attribute = new Attribute(mAttribute, mValue);
			attributeList.add(attribute);
		}
		return accept(node, attributeList);
	}
	
	/**
	 * 属性数组过滤
	 * @param node
	 * @param attributeList
	 * @return
	 */
	private boolean accept(Node node,List<Attribute> attributeList){
		if(attributeList.isEmpty()){
			return false;
		}
		for(Attribute temp:attributeList){
			if(!accept(node, temp)){
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 某一个属性
	 * @param node
	 * @param attribute
	 * @return
	 */
	private boolean accept(Node node,Attribute attribute){
		boolean ret=false;
		if(attribute==null){
			return ret;
		}
		Tag tag;
        if (node instanceof Tag)
        {
            tag = (Tag)node;
            Attribute  tagAttrValue = tag.getAttributeEx (attribute.getName());
            ret = null != tagAttrValue;
            if (ret && (!StringUtils.isBlank(tagAttrValue.getValue()))){
            	if(!StringUtils.isBlank(attribute.getValue())){
            		ret = tagAttrValue.getValue().equals (attribute.getValue ());
            	}
               
            }
        }

        return ret;
	}
	
	

}
